package com.jydd.plug_in_study;

import android.app.Activity;
import android.app.Instrumentation;
import android.os.Handler;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * created by 韦敏敏
 * on 2019/12/25
 */
public class ProxyUtils {
    public static void doInstrumentationHook(Activity activity){
        // 拿到原始的mInstrumentation字段
        Field mInstrumentationFiled = null;
        try {
            mInstrumentationFiled = Activity.class.getDeclaredField("mInstrumentation");
            mInstrumentationFiled.setAccessible(true);
            // 创建代理对象
            Instrumentation originalInstrumentation = (Instrumentation) mInstrumentationFiled.get(activity);
            mInstrumentationFiled.set(activity, new ProxyInstrumentation(originalInstrumentation));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    public static void doHandlerHooker(){
        try {
            Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
            Method currentActivityThread = activityThreadClass.getDeclaredMethod("currentActivityThread");
            Object activityThread = currentActivityThread.invoke(null);
            Field mHField = activityThreadClass.getDeclaredField("mH");
            mHField.setAccessible(true);
            Handler mH = (Handler) mHField.get(activityThread);
            Field mCallbackField = Handler.class.getDeclaredField("mCallback");
            mCallbackField.setAccessible(true);
            mCallbackField.set(mH, new ProxyHandlerCallback(mH));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

}
